package com.aletto.general_store.presenters.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;

import com.aletto.general_store.R;
import com.aletto.general_store.data.model.Goods;
import com.aletto.general_store.data.model.GoodsDetails;
import com.aletto.general_store.data.model.OrderScore;
import com.aletto.general_store.ui.GoodsGridItemDecoration;
import com.aletto.general_store.ui.activities.GoodsCommentActivity;
import com.aletto.general_store.ui.activities.GoodsDetailsActivity;
import com.aletto.general_store.ui.activities.StoreDetailsActivity;
import com.aletto.general_store.ui.adapters.GoodsCommentAdapter;
import com.aletto.general_store.ui.adapters.GoodsCoverBannerAdapter;
import com.aletto.general_store.ui.adapters.GoodsListAdapter;
import com.aletto.general_store.ui.popup.GoodsPopup;
import com.aletto.general_store.utils.GoodsCoverIndicator;
import com.aletto.general_store.utils.LocalConfigStore;
import com.aletto.general_store.utils.Login;
import com.aletto.general_store.utils.ScoreProgress;
import com.aletto.general_store.utils.ToastUtils;
import com.aletto.general_store.utils.XHelper;
import com.aletto.general_store.utils.image.GlideApp;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.lxj.xpopup.XPopup;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.utils.RichTextHelper;
import com.youth.banner.Banner;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import me.jessyan.autosize.utils.AutoSizeUtils;

public class GoodsDetailsView implements INetTask.View<GoodsDetails> {

    private final ViewGroup mParentView, layoutGoodsIntroduce;
    private final View comment_layout;
    private final RatingBar rating_comment_score;
    private final RecyclerView commentRecyclerView, recyclerRecommend;
    private final Banner<String, GoodsCoverBannerAdapter> goodsCoverBanner;
    private final TextView priceUnit, goodsPrice, soldNumber, goodsTitle, goodsPriceOrigin,
            tvCommentScore, tv_comment_number, favoritesButton, buttonBuy;
    private final TextView tv_store_refund_score, tv_service_refund_score;

    private final ScoreProgress store_refund_score, service_refund_score;


    public GoodsDetailsView(ViewGroup parentView) {
        mParentView = parentView;

        buttonBuy = mParentView.findViewById(R.id.button_buy);
        priceUnit = mParentView.findViewById(R.id.tv_price_unit);
        goodsPrice = mParentView.findViewById(R.id.tv_goods_price);
        soldNumber = mParentView.findViewById(R.id.tv_sold_number);
        goodsTitle = mParentView.findViewById(R.id.tv_goods_title);
        favoritesButton = mParentView.findViewById(R.id.button_favorites);
        goodsCoverBanner = mParentView.findViewById(R.id.banner_goods_cover);
        goodsPriceOrigin = mParentView.findViewById(R.id.tv_goods_price_origin);
        layoutGoodsIntroduce = mParentView.findViewById(R.id.layout_goods_introduce);

        // 评论
        tv_store_refund_score = mParentView.findViewById(R.id.text1);
        store_refund_score = mParentView.findViewById(R.id.view_store_refund_score); // 店铺
        tv_service_refund_score = mParentView.findViewById(R.id.text2);
        service_refund_score = mParentView.findViewById(R.id.view_service_refund_score); // 客服

        comment_layout = mParentView.findViewById(R.id.comment_layout);
        tvCommentScore = mParentView.findViewById(R.id.tv_comment_score);
        commentRecyclerView = mParentView.findViewById(R.id.recycler_view);
        tv_comment_number = mParentView.findViewById(R.id.tv_comment_number);
        rating_comment_score = mParentView.findViewById(R.id.rating_comment_score);

        // 推荐
        recyclerRecommend = mParentView.findViewById(R.id.recycler_recommend);
    }

    @Override
    public void success(GoodsDetails data) {
        Context context = mParentView.getContext();
        Goods dataDTO = data.getData();

        String shopId = dataDTO.getShop_id();
        String userId = LocalConfigStore.getInstance().getUserID();
        buttonBuy.setOnClickListener(new Login(v -> {
            if (Objects.equals(shopId, userId)) {
                ToastUtils.makeText(R.string.error_buy_user_id);
                return;
            }

            new XPopup.Builder(buttonBuy.getContext())
                    .asCustom(new GoodsPopup(v.getContext(), dataDTO))
                    .show();
        }));

        goodsTitle.setText(dataDTO.getName()); // 标题
        priceUnit.setText(R.string.price_unit); // 货币单位
        renderGoodsIntroduce(dataDTO.getDesc()); // 介绍
        favoritesButton.setSelected(dataDTO.getIs_like() == 1); // 收藏状态
        goodsPrice.setText(XHelper.toPrice(dataDTO.getPrice())); // 价格
        buttonBuy.setText(String.format(context.getString(R.string.button_buy_text), XHelper.toPrice(dataDTO.getPrice())));
        soldNumber.setText(String.format(context.getString(R.string.placeholder_goods_sold_number), dataDTO.getSales())); // 销售数量

        goodsPriceOrigin.setText( // 原价
                RichTextHelper.newBuilder(dataDTO.getOriginalPriceNumber() + "USDT")
                        .striketrough()
                        .build()
        );

        goodsPriceOrigin.setVisibility( // 显示原价规则
                dataDTO.getOriginalPriceNumber() > dataDTO.getPriceNumber()
                        ? View.VISIBLE
                        : View.INVISIBLE
        );

        // 封面图
        goodsCoverBanner
                .setAdapter(new GoodsCoverBannerAdapter(dataDTO.getGoods_img()))
                .addBannerLifecycleObserver(((LifecycleOwner) context))
                .setIndicator(new GoodsCoverIndicator(context))
                .start();

        // 评论
        GoodsDetails.ScoreDTO scoreDTO = data.getScore();
        if (scoreDTO != null) {

            store_refund_score.setPercentage(scoreDTO.getRefundRate());
            service_refund_score.setPercentage(scoreDTO.getRefundKefuRate());

            tvCommentScore.setText(String.valueOf(scoreDTO.getScore()));
            rating_comment_score.setRating(scoreDTO.getScore());
            tv_store_refund_score.setText(scoreDTO.getRefundRate() + "%"); // 退款
            tv_service_refund_score.setText(scoreDTO.getRefundKefuRate() + "%"); // 客服退款
            tv_comment_number.setText(String.format(context.getString(R.string.comment_score_number), scoreDTO.getScoreCount()));

            List<GoodsDetails.ScoreDTO.ListDTO> scoreDTOList = scoreDTO.getList();
            if (scoreDTOList != null && !scoreDTOList.isEmpty()) {
                comment_layout.setVisibility(View.VISIBLE);

                commentRecyclerView.setAdapter(new GoodsCommentAdapter(
                        scoreDTOList
                                .stream()
                                .map(listDTO -> {
                                    OrderScore user = listDTO.getUser();
                                    OrderScore orderScore = new OrderScore();
                                    orderScore.setGoods_name(dataDTO.getName());
                                    orderScore.setScore(listDTO.getScore());
                                    orderScore.setHead_img(user.getHead_img());
                                    orderScore.setName(user.getName());
                                    return orderScore;
                                })
                                .collect(Collectors.toList())
                ));
            }

        }

        // 推荐
        List<Goods> recommend = data.getRecommend();
        if (recommend != null && !recommend.isEmpty()) {
            recyclerRecommend.addItemDecoration(new GoodsGridItemDecoration(AutoSizeUtils.dp2px(goodsTitle.getContext(), 4)));
            GoodsListAdapter goodsListAdapter = new GoodsListAdapter(recommend);
            recyclerRecommend.setAdapter(goodsListAdapter);

            // 商品详情
            goodsListAdapter.setOnItemClickListener((adapter, view, position) -> {
                Context context1 = view.getContext();
                Goods goods = (Goods) adapter.getItem(position);
                context1.startActivity(GoodsDetailsActivity.newIntent(context1, goods));
            });

            XHelper.setVisibility(View.VISIBLE, mParentView.findViewById(R.id.text_view_11));
        }

        // 进入店铺
        mParentView.findViewById(R.id.tv_goods_store).setOnClickListener(v ->
                context.startActivity(StoreDetailsActivity.newIntent(v.getContext(), shopId)));

        // 更多评论
        mParentView.findViewById(R.id.layout_more_comment).setOnClickListener(v ->
                context.startActivity(GoodsCommentActivity.newIntent(context, dataDTO.getId())));
    }


    // 产品介绍图
    private void renderGoodsIntroduce(List<String> goodsIntroduce) {
        layoutGoodsIntroduce.removeAllViews();
        DisplayMetrics dm = mParentView.getContext().getResources().getDisplayMetrics();

        if (goodsIntroduce != null && !goodsIntroduce.isEmpty()) {
            goodsIntroduce.forEach(s -> {
                ImageView imageView = new ImageView(layoutGoodsIntroduce.getContext());
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                layoutGoodsIntroduce.addView(imageView);

                GlideApp.with(imageView).asBitmap().load(s)
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                float ratio = resource.getWidth() / (float)resource.getHeight();
                                int imageViewHeight = (int) (dm.widthPixels / ratio);

                                imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, imageViewHeight));
                                imageView.setImageBitmap(resource);
                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                            }

                        });
            });
        }
    }

}
